package com.carworld.model;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.alibaba.fastjson.JSONObject;
import com.carworld.model.base.BaseSysUser;
import com.carworld.utils.DateUtils;
import com.carworld.utils.DicUtil;
import com.carworld.utils.EmojiFilter;
import com.carworld.utils.IpUtil;
import com.carworld.utils.MD5;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.ehcache.CacheKit;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.TemplateData;
import com.jfinal.weixin.sdk.api.TemplateMsgApi;
import com.jfinal.weixin.sdk.kit.IpKit;

/**
 * Generated by JFinal.
 */
@SuppressWarnings("serial")
public class SysUser extends BaseSysUser<SysUser> {
	public static final SysUser dao = new SysUser().dao();

	public static final String RANDOM_STRING = "BseaHorace20180922";

	public String getToken(SysUser user) {
		return MD5.md5(
				user.getId() + user.getUserCoins() + user.getScore() + user.getUserIsnew() + SysUser.RANDOM_STRING);
	}

	// 更新用户角色by name and phone
	public void updateUserRole(String role, String userId) {
		SysUser u = this.findById(userId);
		u.setUserRole(role);
		u.update();
		CacheKit.remove(DicUtil.CACHE_SYSUSER, userId);
	}

	public boolean checkToken(SysUser user) {
		if (StrKit.isBlank(user.getUserToken())) {
			return true;
		}
		return user.getUserToken().equals(this.getToken(user));
	}

	/**
	 * 查询用户基本信息 by userId
	 */
	public SysUser findByIdInCache(String id) {
		String sqlString = "SELECT su.id, su.company_id, su.name, su.mobile,su.userPosition,su.score, su.user_nickname, su.user_photo, su.user_openId, su.user_coins, su.user_isNew, su.user_isFocus, su.user_register_time,su.user_role, su.user_sex, su.user_isVerificated, su.user_of_shareholder, su.dividend_workerid, su.user_total_consumption FROM sys_user su  WHERE su.id = ? ";
		return this.findFirstByCache(DicUtil.CACHE_SYSUSER, id, sqlString, id);
	}

	/**
	 * 查询用户基本信息by openId
	 */
	public SysUser findByOpenIdInCache(String openId) {
		String sqlString = "SELECT su.id, su.company_id, su.name, su.mobile,su.userPosition,su.score, su.user_nickname, su.user_photo, su.user_openId, su.user_coins, su.user_isNew, su.user_isFocus, su.user_register_time,su.user_role, su.user_sex, su.user_isVerificated, su.user_of_shareholder, su.dividend_workerid, su.user_total_consumption FROM sys_user su  WHERE su.user_openId = ? ";
		return this.findFirstByCache(DicUtil.CACHE_SYSUSER, openId, sqlString, openId);
	}

	/**
	 * 保存用户的基本信息
	 */
	public void save(JSONObject userJson, Controller con) {
		String openId = userJson.getString("openid");
		SysUser exsitedUserByOpenId = this.findByOpenIdInCache(openId); // By OpenId
		SysUser exsitedUserById = this.findByIdInCache(con.getCookie("cid")); //
		Date date = new Date();
		String nickName = EmojiFilter.filterEmoji(userJson.getString("nickname")) ;
		if (null != exsitedUserByOpenId && null != exsitedUserById) { 	// 将微信端用户信息补充到后台端用户信息中，更新cookie中的id再删除微信端用户
			System.out.println("后台端、微信端信息都存在");
			exsitedUserById.setUserOpenid(userJson.getString("openid"));
			exsitedUserById.setUserToken(exsitedUserByOpenId.getUserToken());
			exsitedUserById.setUserPhoto(userJson.getString("headimgurl"));
			exsitedUserById.setUserNickname(nickName);
			exsitedUserById.setUserSex(userJson.getString("sex"));
			// exsitedUserById.setUserIsfocus(userJson.getString("subscribe"));
			String ip = IpKit.getRealIp(con.getRequest());
			if (StrKit.isBlank(ip)) {
				ip = "127.0.0.1";
			}
			ip = ip.replace("，", ",");
			if (ip.indexOf(",") != -1) {
				ip = ip.split(",")[0];
			}
			exsitedUserById.setUserIp(ip);
			JSONObject data = IpUtil.parsing(ip);
			if (null != data) {
				exsitedUserById.setUserProvince(data.getString("region"));
				exsitedUserById.setUserCity(data.getString("city"));
			}
			exsitedUserById.setUserUpdateTime(date);
			exsitedUserById.setUserGetinfoTime(date);
			exsitedUserById.setUserIsnew("0"); // 是否为新用户:默认为0-新用户
			exsitedUserById.setUserIsVerificated("1"); // 认证通过，状态设置为 1
			exsitedUserById.setUserRegisterTime(date);
			exsitedUserById.setCompanyId("a6134faf9a844fe0ae006c7bd1d9a6d5"); // 12.8临时绑定为茉德精品火锅客户
			exsitedUserById.update();
			con.removeCookie("cid");
			con.setCookie("cid", exsitedUserById.getId(), 30 * 24 * 60 * 60);
			CacheKit.remove(DicUtil.CACHE_SYSUSER, exsitedUserByOpenId.getId());
			CacheKit.remove(DicUtil.CACHE_SYSUSER, exsitedUserByOpenId.getUserOpenid());
			exsitedUserByOpenId.deleteById(exsitedUserByOpenId.getId());

		} else if (null == exsitedUserByOpenId && null != exsitedUserById) {
			System.out.println("后台端用户信息存在，微信端信息不存在");
			exsitedUserById.setUserOpenid(userJson.getString("openid"));
			exsitedUserById.setUserPhoto(userJson.getString("headimgurl"));
			exsitedUserById.setUserNickname(nickName);
			exsitedUserById.setUserSex(userJson.getString("sex"));
			exsitedUserById.setUserIsfocus(userJson.getString("subscribe"));
			String ip = IpKit.getRealIp(con.getRequest());
			if (StrKit.isBlank(ip)) {
				ip = "127.0.0.1";
			}
			ip = ip.replace("，", ",");
			if (ip.indexOf(",") != -1) {
				ip = ip.split(",")[0];
			}
			exsitedUserById.setUserIp(ip);
			JSONObject data = IpUtil.parsing(ip);
			if (null != data) {
				exsitedUserById.setUserProvince(data.getString("region"));
				exsitedUserById.setUserCity(data.getString("city"));
			}
			exsitedUserById.setUserUpdateTime(new Date());
			exsitedUserById.setUserGetinfoTime(new Date());
			exsitedUserById.setUserIsVerificated("1"); // 会员认证通过，状态设置为 1
			exsitedUserById.setUserRegisterTime(new Date());
			exsitedUserById.setCompanyId("a6134faf9a844fe0ae006c7bd1d9a6d5");
			exsitedUserById.update();

			con.removeCookie("cid");
			con.setCookie("cid", exsitedUserById.getId(), 30 * 24 * 60 * 60);
			CacheKit.remove(DicUtil.CACHE_SYSUSER, exsitedUserById.getUserOpenid());
			CacheKit.remove(DicUtil.CACHE_SYSUSER, exsitedUserById.getId());
		} else if (null != exsitedUserByOpenId && null == exsitedUserById) {
			// 如果cookie的缓存失效，会进入这里
			System.out.println("存在之前的微信用户信息，即为同一个用户登录");
			con.removeCookie("cid");
			con.setCookie("cid", exsitedUserByOpenId.getId(), 30 * 24 * 60 * 60);
			//exsitedUserByOpenId.setUserIsfocus(userJson.getString("subscribe"));
			exsitedUserByOpenId.update();
			CacheKit.remove(DicUtil.CACHE_SYSUSER, exsitedUserByOpenId.getUserOpenid());
			CacheKit.remove(DicUtil.CACHE_SYSUSER, exsitedUserByOpenId.getId());

		} else {
			System.out.println("此为全新用户");
			SysUser user = new SysUser();
			String userId = getIds();// 随机生成用户id
			user.setId(userId);
			user.setName(nickName);
			user.setUserPhoto(userJson.getString("headimgurl"));
			user.setUserNickname(nickName);
			String ip = IpKit.getRealIp(con.getRequest());
			if (StrKit.isBlank(ip)) {
				ip = "127.0.0.1";
			}
			ip = ip.replace("，", ",");
			if (ip.indexOf(",") != -1) {
				ip = ip.split(",")[0];
			}
			user.setUserIp(ip);
			JSONObject data = IpUtil.parsing(ip);
			if (null != data) {
				user.setUserProvince(data.getString("region"));
				user.setUserCity(data.getString("city"));
			}
			user.setUserOpenid(openId);
			user.setUserSex(userJson.getString("sex"));
			user.setUserIsfocus(userJson.getString("subscribe"));
			user.setUserGetinfoTime(date);
			user.setUserRegisterTime(date);
			user.setUserToken(SysUser.dao.getToken(user));
			user.setCompanyId("a6134faf9a844fe0ae006c7bd1d9a6d5");
			user.save();
			con.setCookie("cid", userId, 30 * 24 * 60 * 60);
		}

	}

	/**
	 * 通过手机号和名字进行会员身份验证
	 */
	public SysUser getValiation(String userName, String mobile) {
		String sqlString = "select uc.* from sys_user uc where uc.name= ? and uc.mobile= ?";
		return this.findFirstByCache(DicUtil.CACHE_SYSUSER, userName + mobile, sqlString, userName, mobile);
	}

	/**
	 * 通过手机号和名字进行会员身份验证
	 */
	public String getNickname() {
		return "会员" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + (int) (Math.random() * 90 + 10);
	}

	/**
	 * 领取会员卡
	 */
	public JSONObject bindMember(String shareBy, String userId) {
		JSONObject jsonObject = new JSONObject();
		String message = null;
		// 查询分享者的基本信息
		System.out.println("开始查询分享者信息");
		SysUser sharerInfo = SysUser.dao.findByIdInCache(shareBy);
		System.out.println("sharerInfo的基本信息：" + sharerInfo.toString());
		String sharerRole = sharerInfo.getUserRole();

		// 查询新会员的基本信息
		SysUser userInfo = SysUser.dao.findByIdInCache(userId);

		if (null != sharerInfo && ("1".equals(sharerRole) || "4".equals(sharerRole))) {
			if (null == userInfo.getUserOfShareholder()) {
				userInfo.setUserOfShareholder(shareBy);
				userInfo.setCompanyId(sharerInfo.getCompanyId());
				userInfo.update();
				// 新建会员卡
				Date date = new Date();
				Card card = new Card();
				long cardId = date.getTime();
				card.setGroupid(sharerInfo.getCompanyId());
				card.setCardid(cardId);
				card.setAmt(new BigDecimal(0.00));
				card.setAvaiabletime(365);
				card.setIsshared("是");
				card.setSource("门店");
				card.setStatus("使用");
				card.setCardcode(userInfo.getMobile());
				card.setCardname("【"+userInfo.getName()+userInfo.getMobile()+"】茉德会员卡");
				card.setComment("来源于会员[" + sharerInfo.getName() + "]分享二维码");
				card.setCreateTime(date);
				card.setUserId(userId);
				card.setUserOfShareholder(shareBy);
				card.setShareBy(shareBy);
				card.setRemainingNum(1);
				card.setSharingNum(0);
				card.save();
				message = "恭喜您成为【茉德精品火锅】会员~";
				ApiResult apiResult = TemplateMsgApi.send(TemplateData.New().setTouser(sharerInfo.getUserOpenid())// 消息接收者
						.setTemplate_id("UbYIaemotFVVG2O0jWdUeALtEDSaDJZA9nTZePcpLUk") // 新会员加入的模板id
						.setUrl("http://food.3kkk.xyz/carworld_weixin/pages/page_userCenter/myMembers.html")
						// 模板参数
						.add("first", "您有新的人脉会员加入\n")
						.add("keyword1", DateUtils.getCurrentTime(new Date()) + "\n", "#173177")
						.add("keyword2", userInfo.getUserNickname(), "#173177").add("keyword3", "茉德精品火锅普通会员", "#173177")
						.add("keyword4", DateUtils.getCurrentTime(new Date()) + "\n", "#173177")
						.add("remark", "该会员通过您的推广码加入，推广效果显著，继续加油哦~", "#173177").build());
				System.out.println("通推广者模板消息结果：" + apiResult.getJson());

			} else {
				message = "您已经是会员，邀请失败~";
				System.out.println("您已经是会员，邀请失败~");
				jsonObject.put("state", "-1");
			}
		}
		if (null != sharerInfo && "3".equals(sharerRole)) {
			if (null == userInfo.getDividendWorkerId()) {
				userInfo.setDividendWorkerId(sharerInfo.getDividendWorkerId());
				userInfo.setDividendWorkerId(shareBy);
				userInfo.setCompanyId(sharerInfo.getCompanyId());
				// 新建会员卡
				Date date = new Date();
				Card card = new Card();
				long cardId = date.getTime();
				card.setGroupid(sharerInfo.getCompanyId());
				card.setCardid(cardId);
				card.setAmt(new BigDecimal(0.00));
				card.setAvaiabletime(365);
				card.setIsshared("是");
				card.setSource("门店");
				card.setStatus("使用");
				card.setCardcode(userInfo.getMobile());
				card.setCardname("【"+userInfo.getName()+userInfo.getMobile()+"】茉德会员卡");
				card.setComment("来源店员[" + sharerInfo.getName() + "]分享二维码");
				card.setCreateTime(date);
				card.setUserId(userId);
				card.setUserOfShareholder(shareBy);
				card.setShareBy(shareBy);
				card.setRemainingNum(1);
				card.setSharingNum(0);
				card.save();

				message = "恭喜您成为【茉德精品火锅】会员";

			} else {
				message = "您已经是会员，邀请失败~";
				System.out.println("您已经是会员，邀请失败~");
				jsonObject.put("state", "-1");
			}
		}
		userInfo.update();

		// 清除缓存
		CacheKit.remove(DicUtil.CACHE_SYSUSER, userId);

		jsonObject.put("message", message);
		jsonObject.put("officeAddress", "5/445Victoria Ave Chatswood NSW 2067");
		jsonObject.put("officeName", "茉德精品火锅");
		jsonObject.put("sharerName", sharerInfo.getName());
		jsonObject.put("sharerPhoto", sharerInfo.getUserPhoto());
		jsonObject.put("userIsFocus", userInfo.getUserIsfocus());
		return jsonObject;
	}

}
